
package com.yanboo.generator.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.yanboo.common.config.FileProperties;
import com.yanboo.common.exception.BadRequestException;
import com.yanboo.common.utils.*;

import com.yanboo.generator.domain.DriverLocalStorage;
import com.yanboo.generator.properties.DriverStorageProperties;
import com.yanboo.generator.repository.DriverLocalStorageRepository;
import com.yanboo.generator.service.DriverLocalStorageService;
import com.yanboo.generator.service.dto.DriverLocalStorageDto;
import com.yanboo.generator.service.dto.DriverLocalStorageQueryCriteria;
import com.yanboo.generator.service.mapstruct.DriverLocalStorageMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


@Service
@RequiredArgsConstructor
public class DriverLocalStorageServiceImpl implements DriverLocalStorageService {

    private final DriverLocalStorageRepository localStorageRepository;
    private final DriverLocalStorageMapper localStorageMapper;
    private final DriverStorageProperties properties;

    @Override
    public PageResult<DriverLocalStorageDto> queryAll(DriverLocalStorageQueryCriteria criteria, Pageable pageable){
        Page<DriverLocalStorage> page = localStorageRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(localStorageMapper::toDto));
    }

    @Override
    public List<DriverLocalStorageDto> queryAll(DriverLocalStorageQueryCriteria criteria){
        return localStorageMapper.toDto(localStorageRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public DriverLocalStorageDto findById(Long id){
        DriverLocalStorage localStorage = localStorageRepository.findById(id).orElseGet(DriverLocalStorage::new);
        ValidationUtil.isNull(localStorage.getId(),"LocalStorage","id",id);
        return localStorageMapper.toDto(localStorage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DriverLocalStorage create(String name, MultipartFile multipartFile) {
        String suffix = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
       // String type = FileUtil.getFileType(suffix);
        File file = FileUtil.upload(multipartFile, properties.getPath() +  File.separator);
        if(ObjectUtil.isNull(file)){
            throw new BadRequestException("上传失败");
        }
        try {
            name = StringUtils.isBlank(name) ? FileUtil.getFileNameNoEx(multipartFile.getOriginalFilename()) : name;
            DriverLocalStorage localStorage = new DriverLocalStorage(
                    file.getName(),
                    name,
                    suffix,
                    file.getPath(),
                    "jar",
                    FileUtil.getSize(multipartFile.getSize())
            );
            return localStorageRepository.save(localStorage);
        }catch (Exception e){
            FileUtil.del(file);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DriverLocalStorage resources) {
        DriverLocalStorage localStorage = localStorageRepository.findById(resources.getId()).orElseGet(DriverLocalStorage::new);
        ValidationUtil.isNull( localStorage.getId(),"LocalStorage","id",resources.getId());
        localStorage.copy(resources);
        localStorageRepository.save(localStorage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            DriverLocalStorage storage = localStorageRepository.findById(id).orElseGet(DriverLocalStorage::new);
            FileUtil.del(storage.getPath());
            localStorageRepository.delete(storage);
        }
    }

    @Override
    public void download(List<DriverLocalStorageDto> queryAll, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DriverLocalStorageDto localStorageDTO : queryAll) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("文件名", localStorageDTO.getRealName());
            map.put("备注名", localStorageDTO.getName());
            map.put("文件类型", localStorageDTO.getType());
            map.put("文件大小", localStorageDTO.getSize());
            map.put("创建者", localStorageDTO.getCreateBy());
            map.put("创建日期", localStorageDTO.getCreateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}
